package it.eng.get.pdfwe.fillers.jr;

import it.eng.get.pdfwe.fillers.ModelFiller;
import it.eng.get.pdfwe.jr.PropertyLoader;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ClassUtils;


public class JRFillerFactory {

	private static final Logger logger = Logger.getLogger(JRFillerFactory.class.getName());
	
	private static Class getJRFillerBean(String reportName) {
		String clName = PropertyLoader.getFillers().get(reportName);
		if (clName!=null) {
			try {
				return Class.forName(clName);
			} catch (Exception e) {
				logger.severe("Non posso trovare la classe con nome " + clName);
				e.printStackTrace();
			}
		} else logger.severe("Non posso trovare la classe per il report " + reportName);
		logger.info("Uso il filler di default (vuoto) per il report " + reportName);
		return JREmptyFiller.class;
		
	} 
	

	public static JRFillerBean getFiller(HttpServletRequest request) throws Exception {
		String reportName = request.getParameter("reportName");
		if (reportName==null) throw new Exception("Il nome del report e' null");
		
		
		try { // Provo ad usare la reflection con la Naming convention: class JRFiller<nomeReport>
			String absoluteRptName = reportName.replaceAll("\\.jasper$" , "");
			Class afiller = getJRFillerBean(absoluteRptName);
			
			if (ClassUtils.isAssignable(afiller,ModelFiller.class )) {
				Constructor c = afiller.getConstructor(HttpServletRequest.class);
				ModelFiller filler = (ModelFiller)c.newInstance(request);
				return (JRFillerBean) filler.getData();
			} else throw new Exception("La classe " + afiller.getName() + " deve estendere JRFiller");
			
		} catch (Exception e) {
			e.printStackTrace();
//			throw new Exception("Non e' stato possibile popolare il report " + reportName);
			
		}
		return new JREmptyFiller(request).getData();
	}

	
	
	/**
	 * @deprecated
	 * @param reportName
	 * @param reportParams
	 * @return
	 * @throws Exception
	 */
	public static JRFillerBean getData(String reportName,List reportParams) throws Exception {
		if (reportName==null) throw new Exception("Il nome del report e' null");
		throw new Exception("Non e' stato possibile popolare il report " + reportName);		
	}

	
}
